package cn.xianshu.quartz.job;

import cn.xianshu.order.domain.OrderPet;
import cn.xianshu.order.domain.OrderPetDetail;
import cn.xianshu.order.mapper.OrderPetDetailMapper;
import cn.xianshu.order.mapper.OrderPetMapper;
import cn.xianshu.pay.domain.PayBill;
import cn.xianshu.pay.service.IPayBillService;
import cn.xianshu.pet.domain.Pet;
import cn.xianshu.pet.mapper.PetMapper;
import cn.xianshu.quartz.util.QuartzUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.common.models.AlipayTradeCloseResponse;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

// 工作类、交给容器管理
// 订单超时处理的工作
@Component
public class OrderExpireJob implements Job {
    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private OrderPetMapper orderPetMapper;

    @Autowired
    private OrderPetDetailMapper orderPetDetailMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private Scheduler scheduler;



    /**
     * 订单超时业务分析
     * 1.获取订单支付单数据
     * 2.如果支付单为待支付，将状态改为超时状态
     * 3.查询业务单，将状态修改为超时
     * 4.查询宠物信息，将库存退回去
     * 5.调用支付宝关闭支付接口
     * 6.删除定时任务
     */
    @Override
    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 订单超时业务分析
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap(); // 获取数据
        // 数据
        Map<String, String> dataMap = (Map<String, String>) jobDataMap.get("params"); // 获取params中的数据
        String orderNo = dataMap.get("orderNo"); // 获取订单号

        // 1.获取订单支付单数据
        PayBill payBill = payBillService.selectByNo(orderNo);
        // 获取订单名
        String jobName = dataMap.get("jobName");

        // 2.如果支付单为待支付，将状态改为超时状态
        if (payBill.getState().intValue() != PayBill.SATET_WAIT_PAY){
            QuartzUtil.removeJob(scheduler, jobName);
            System.out.println("删除定时任务!");
            return;
        }


        OrderPet orderPet = orderPetMapper.selectByOrderNo(orderNo);
        if (orderPet.getState().intValue() != PayBill.SATET_WAIT_PAY){
                QuartzUtil.removeJob(scheduler, jobName);
                System.out.println("删除定时任务!");
                return;
        }


        payBill.setState(PayBill.SATET_CANCEL); // 将状态改为超时状态!
        Date date = new Date();
        payBill.setLastPayTime(date);// 支付最后修改时间
        payBillService.update(payBill); // 提交修改数据

        // 3.查询业务单，将状态修改为超时
        orderPet.setState(OrderPet.STATE_PAY_OUTTIME_CANCEL);
        orderPet.setLastUpdateTime(date);
        orderPetMapper.update(orderPet); // 修改业务单

        // 4.查询宠物信息，将库存退回去
        List<OrderPetDetail> details = orderPetDetailMapper.selectByOrderNo(orderNo);
        // 宠物id集合
        List<Long> list = details.stream().map(detail -> detail.getPetId()).collect(Collectors.toList());
        List<Pet> pets = petMapper.selectloadById(list, Pet.OFFSALE_ID);
        // 遍历 将所有的库存都退回
        pets.forEach(pet -> {
            //这里的1按道理应该是加：OrderPetDetail中的数量
            pet.setStore_number(pet.getStore_number() + 1);
            petMapper.update(pet);
        });

        // 5.调用支付宝关闭支付接口
        try {
            AlipayTradeCloseResponse response = Factory.Payment.Common().close(orderNo);
            System.out.println("支付宝关闭订单:" + response);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 6.删除定时任务
        QuartzUtil.removeJob(scheduler, jobName);
        System.out.println("成功删除定时任务!");

    }
}
